package com.sbtr.business.trainingserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sbtr.business.trainingmodel.service.ITrainingModelDataService;
import com.sbtr.business.trainingserver.service.IPublishServerHttpApi;
import com.sbtr.constant.ProjectConstant;
import com.sbtr.exception.BizException;
import com.sbtr.open.importmodel.dto.ImportModelTaskDto;
import com.sbtr.open.publishtask.dto.PublishTaskDataDto;
import com.sbtr.open.trainingmodel.dto.TrainingModelDataDto;
import com.sbtr.open.trainingserver.dto.TrainingServerDto;
import com.sbtr.open.trainingtask.dto.TrainingInfoDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.RestTemplate;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class PublishServerHttpApiImpl implements IPublishServerHttpApi {

	private static final Logger logger = LoggerFactory.getLogger(PublishServerHttpApiImpl.class);

	private static final String HTTP = "http://";
	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private ITrainingModelDataService trainingModelService;

//	@Autowired
//	private OSSUtil ossUtil;

	@Value("${training-task.sdk-base-dir}")
	private String sdkPath;

//	@Override
//	public boolean addTask(TrainingServerDto serverDto, TrainingTaskDto trainingTaskDto, PublishTaskDto publishTaskDto,
//			TrainingModelDto trainingModelDto) {
//		String url = HTTP + serverDto.getIp() + "/addTask";
//		logger.info("启动部署任务请求地址:{} ", url);
//		HttpHeaders headers = this.initRestTemplateHeader();
//
//		Map<String, Object> postParameters = new HashMap<>();
//		postParameters.put("taskid", publishTaskDto.getId().toString());
//		postParameters.put("tasktype", trainingTaskDto.getType().equals("9") ? 0L : Long.parseLong(trainingTaskDto.getType()));
//		postParameters.put("classnum", Long.parseLong(trainingTaskDto.getClassNum()));
//		postParameters.put("modelweight", trainingModelDto.getModelDir());
//		//是否使用数据增强 0.0-1.0 暂时有鸡哥那边默认 postParameters.put("augmentpersent", 0.2);
//		String jsonBody = JSON.toJSONString(postParameters);
//		logger.info("启动部署任务参数:{} ", jsonBody);
//		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
//		ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);
//
//		// 返回结果
//		String body = postForEntity.getBody();
//		JSONObject jsObj = JSONObject.parseObject(body);
//		if (jsObj.getInteger("ret") != null && 0 == jsObj.getInteger("ret")) {
//			return true;
//		} else {
//			Integer ret = jsObj.getInteger("ret") != null ? jsObj.getInteger("ret") : 0;
//			String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
//			logger.error("状态码:{},msg:{}", ret, msg);
//			throw new BizException(msg);
//		}
//
//	}



//	@Override
//	public boolean addTaskData(TrainingServerDto serverDto, TrainingTaskDataDto trainingTaskDataDto,
//			PublishTaskDataDto publishTaskDataDto, TrainingModelDataDto trainingModelDto) {
//		String url = HTTP + serverDto.getIp() + "/api/create";
//		logger.info("启动部署任务请求地址:{}", url);
//		HttpHeaders headers = this.initRestTemplateHeader();
//
//		Map<String, Object> postParameters = new HashMap<>();
//		postParameters.put("task_id", publishTaskDataDto.getId());
//		postParameters.put("task_type", Long.parseLong(trainingTaskDataDto.getType()));
//		postParameters.put("model_name", trainingModelDto.getModelDir());
//
//		String mapsObject = trainingModelDto.getClassifier();
//		try {
//			JSONObject maps = JSONObject.parseObject(mapsObject);
//			postParameters.put("maps", maps);
//			JSONArray variableName = maps.getJSONArray("feature_name");
//			postParameters.put("variable_name", variableName);
//			if (maps.containsKey("date_name")) {
//				JSONArray dateName = maps.getJSONArray("date_name");
//				postParameters.put("date_name", dateName);
//			}
//		} catch (Exception e) {
//			logger.error("启动预测API时，映射关系转换json出错");
//			throw new BizException("启动预测API时，映射关系转换json出错");
//		}
//
//		String jsonBody = JSON.toJSONString(postParameters);
//		logger.info("启动部署任务参数:{}", jsonBody);
//		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
//		ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);
//
//		// 返回结果
//		String body = postForEntity.getBody();
//		JSONObject jsObj = JSONObject.parseObject(body);
//		if (jsObj.getInteger("code") != null && 200 == jsObj.getInteger("code")) {
//			return true;
//		} else {
//			Integer ret = jsObj.getInteger("code") != null ? jsObj.getInteger("code") : 0;
//			String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
//			String data = StringUtils.isNotBlank(jsObj.getString("data")) ? jsObj.getString("data") : "";
//			logger.error("状态码:{}, msg:{}, data:{}", ret, msg, data);
//			throw new BizException(ret, msg, data);
//		}
//	}

	//发布外部模型
	@Override
	public String publishExternalModel(TrainingServerDto serverDto, ImportModelTaskDto task){
		String url = HTTP + serverDto.getIp() + "/api/create";
		logger.info("启动部署任务请求地址:{}", url);
		HttpHeaders headers = this.initRestTemplateHeader();

		Map<String, Object> postParameters = new HashMap<>();
		postParameters.put("task_id", task.getId());//
		postParameters.put("task_type", task.getModelFileType());
		postParameters.put("file_id", "");
		postParameters.put("model_name", task.getFilePath());//外部模型的路径(必须是真实模型文件)

		JSONObject maps = JSONObject.parseObject("{'label': {}, 'feature': {}}");
		postParameters.put("maps", maps);

//			JSONArray variableName = maps.getJSONArray("feature_name");
			postParameters.put("variable_name", "");
//			if (maps.containsKey("date_name")) {
//				JSONArray dateName = maps.getJSONArray("date_name");
				postParameters.put("date_name", "");
//			}
//		} catch (Exception e) {
//			logger.error("启动预测API时，映射关系转换json出错");
//			throw new BizException("启动预测API时，映射关系转换json出错");
//		}

		String jsonBody = JSON.toJSONString(postParameters);
		logger.info("启动部署任务参数:{}", jsonBody);
		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
		ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);//发http请求

		// 返回结果
		String body = postForEntity.getBody();
		JSONObject jsObj = JSONObject.parseObject(body);
		if (jsObj.getInteger("code") != null && 200 == jsObj.getInteger("code")) {
			return body;
		} else {
			Integer ret = jsObj.getInteger("code") != null ? jsObj.getInteger("code") : 0;
			String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
			String data = StringUtils.isNotBlank(jsObj.getString("data")) ? jsObj.getString("data") : "";
			logger.error("状态码:{}, msg:{}, data:{}", ret, msg, data);
			throw new BizException(ret, msg, data);
		}

	}

	//发布外部模型
	@Override
	public boolean publishExternalModel2(TrainingServerDto serverDto,
										 PublishTaskDataDto publishTaskDataDto, TrainingModelDataDto trainingModelDataDto){
		String url = HTTP + serverDto.getIp() + "/api/create";
		logger.info("启动部署任务请求地址:{}", url);
		HttpHeaders headers = this.initRestTemplateHeader();

		Map<String, Object> postParameters = new HashMap<>();
		postParameters.put("task_id", publishTaskDataDto.getId());//
		postParameters.put("task_type", trainingModelDataDto.getModelFileType());
		postParameters.put("file_id", "");
		postParameters.put("model_name", trainingModelDataDto.getModelDir());//外部模型的路径(必须是真实模型文件)

		JSONObject maps = JSONObject.parseObject("{'label': {}, 'feature': {}}");
		postParameters.put("maps", maps);

//			JSONArray variableName = maps.getJSONArray("feature_name");
		postParameters.put("variable_name", "");
//			if (maps.containsKey("date_name")) {
//				JSONArray dateName = maps.getJSONArray("date_name");
		postParameters.put("date_name", "");
//			}
//		} catch (Exception e) {
//			logger.error("启动预测API时，映射关系转换json出错");
//			throw new BizException("启动预测API时，映射关系转换json出错");
//		}

		String jsonBody = JSON.toJSONString(postParameters);
		logger.info("启动部署任务参数:{}", jsonBody);
		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
//		ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);//发http请求

		AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();

		ListenableFuture<ResponseEntity<String>> forEntity = asyncRestTemplate.postForEntity(url, r, String.class);

		forEntity.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
			@Override
			public void onFailure(Throwable ex) {
				logger.error(String.format("POST回调 %s 参数为 %s 请求失败，%s", url, JSON.toJSONString(r), ex.getMessage()));
			}
			@Override
			public void onSuccess(ResponseEntity<String> result) {
				logger.info(String.format("POST回调 %s 参数为 %s 请求成功，返回值为 %s", url, JSON.toJSONString(r), JSON.toJSONString(result.getBody())));
			}
		});
		return true;

		// 返回结果
//		String body = postForEntity.getBody();
//		JSONObject jsObj = JSONObject.parseObject(body);
//		if (jsObj.getInteger("code") != null && 200 == jsObj.getInteger("code")) {
//			TrainingModelData model = BeanCopyUtils.copyProperties(trainingModelDataDto, TrainingModelData.class);
//			String api = HTTP + serverDto.getIp() + "/api/" + publishTaskDataDto.getId() + "/customPredict";
//			model.setApi(api);
//			model.setStatus(TrainingModelDataDto.MODEL_STATUS_PUBLISHED);
//			trainingModelService.updateById(model);
//			return true;
//		} else {
//			Integer ret = jsObj.getInteger("code") != null ? jsObj.getInteger("code") : 0;
//			String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
//			String data = StringUtils.isNotBlank(jsObj.getString("data")) ? jsObj.getString("data") : "";
//			logger.error("状态码:{}, msg:{}, data:{}", ret, msg, data);
//			throw new BizException(ret, msg, data);
//		}

	}

	@Override
	public boolean addTaskData2(TrainingServerDto serverDto, TrainingInfoDto trainingInfoDto,
							   PublishTaskDataDto publishTaskDataDto, TrainingModelDataDto trainingModelDto) {
		String url = HTTP + serverDto.getIp() + "/api/create";
		logger.info("启动部署任务请求地址:{}", url);
		HttpHeaders headers = this.initRestTemplateHeader();

		Map<String, Object> postParameters = new HashMap<>();
		postParameters.put("task_id", publishTaskDataDto.getId());
		postParameters.put("task_type", Long.parseLong(trainingInfoDto.getType()));
		postParameters.put("file_id", trainingInfoDto.getFileId());
		postParameters.put("model_name", trainingModelDto.getModelDir());

		String mapsObject = trainingModelDto.getClassifier();
		try {
			JSONObject maps = JSONObject.parseObject(mapsObject);
			postParameters.put("maps", maps);
			JSONArray variableName = maps.getJSONArray("feature_name");
			postParameters.put("variable_name", variableName);
			if (maps.containsKey("date_name")) {
				JSONArray dateName = maps.getJSONArray("date_name");
				postParameters.put("date_name", dateName);
			}
		} catch (Exception e) {
			logger.error("启动预测API时，映射关系转换json出错");
			throw new BizException("启动预测API时，映射关系转换json出错");
		}

		String jsonBody = JSON.toJSONString(postParameters);
		logger.info("启动部署任务参数:{}", jsonBody);
		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);

//		ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);

		AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();

		ListenableFuture<ResponseEntity<String>> forEntity = asyncRestTemplate.postForEntity(url, r, String.class);

		forEntity.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
			@Override
			public void onFailure(Throwable ex) {
				logger.error(String.format("POST回调 %s 参数为 %s 请求失败，%s", url, JSON.toJSONString(r), ex.getMessage()));
			}
			@Override
			public void onSuccess(ResponseEntity<String> result) {
				logger.info(String.format("POST回调 %s 参数为 %s 请求成功，返回值为 %s", url, JSON.toJSONString(r), JSON.toJSONString(result.getBody())));
			}
		});
		return true;

		// 返回结果
		/*
		String body = postForEntity.getBody();
		JSONObject jsObj = JSONObject.parseObject(body);
		if (jsObj.getInteger("code") != null && 200 == jsObj.getInteger("code")) {
			TrainingModelData model = BeanCopyUtils.copyProperties(trainingModelDto, TrainingModelData.class);
			String api = HTTP + serverDto.getIp() + "/api/" + publishTaskDataDto.getId() + "/customPredict";
			model.setApi(api);
			model.setStatus(TrainingModelDataDto.MODEL_STATUS_PUBLISHED);
			trainingModelService.updateById(model);
			return true;
		} else {
			Integer ret = jsObj.getInteger("code") != null ? jsObj.getInteger("code") : 0;
			String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
			String data = StringUtils.isNotBlank(jsObj.getString("data")) ? jsObj.getString("data") : "";
			logger.error("状态码:{}, msg:{}, data:{}", ret, msg, data);
			throw new BizException(ret, msg, data);
		}*/
	}



	@Override
	public boolean stopTask(TrainingServerDto serverDto, long taskId) {
		String url = HTTP + serverDto.getIp() + "/stopTask";
		logger.info("下线部署任务请求地址:{}", url);
		HttpHeaders headers = this.initRestTemplateHeader();

		Map<String, Object> postParameters = new HashMap<>();
		postParameters.put("taskid", taskId + "");
		String jsonBody = JSON.toJSONString(postParameters);
		logger.info("下线部署任务参数:{}", jsonBody);
		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
		try {
			ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);
			// 返回结果
			String body = postForEntity.getBody();
			JSONObject jsObj = JSONObject.parseObject(body);
			if (jsObj.getInteger("ret") != null && 0 == jsObj.getInteger("ret")) {
				return true;
			} else {
				Integer ret = jsObj.getInteger("ret") != null ? jsObj.getInteger("ret") : 0;
				String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
				logger.error("状态码:{}, msg:{}", ret, msg);
				//保证GPU重启 任务可以正常下线成功
				if(ret == 20001 && msg.equals("Task not in queue!")) {
					return true;
				}
				throw new BizException(msg);
			}
		} catch (Exception e) {
			logger.error("gpu服务器调用异常:{}", e.getMessage());
			throw new RuntimeException("gpu服务器调用异常", e);
		}
	}
	
	@Override
	public List<TaskInfo> getTaskList(TrainingServerDto serverDto) {
		String url = HTTP + serverDto.getIp() + "/getTaskList";
		HttpHeaders headers = this.initRestTemplateHeader();

		Map<String, Object> postParameters = new HashMap<>();
		String jsonBody = JSON.toJSONString(postParameters);
		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
		ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);

		// 返回结果
		String body = postForEntity.getBody();
		JSONObject jsObj = JSONObject.parseObject(body);
		if (jsObj.getInteger("ret") != null && 0 == jsObj.getInteger("ret")) {
			JSONArray jsonArray = jsObj.getJSONArray("tasklist");
			return jsonArray.toJavaList(TaskInfo.class);
		} else {
			Integer ret = jsObj.getInteger("ret") != null ? jsObj.getInteger("ret") : 0;
			String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
			logger.error("状态码:{}, msg:{}", ret, msg);
		}
		return Collections.emptyList();
	}

	@Override
	public boolean stopTaskData(TrainingServerDto serverDto, long taskId) {
		String url = HTTP + serverDto.getIp() + "/api/" + taskId + "/stop";
		logger.info("下线部署任务请求地址:{}", url);

		try {
			ResponseEntity<String> getForEntity = restTemplate.getForEntity(url, String.class);
			// 返回结果
			String body = getForEntity.getBody();

			JSONObject jsObj = JSONObject.parseObject(body);
			if (jsObj.getInteger("code") != null && 200 == jsObj.getInteger("code")) {
				return true;
			} else {
				Integer code = jsObj.getInteger("code") != null ? jsObj.getInteger("code") : 0;
				String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
				String data = StringUtils.isNotBlank(jsObj.getString("data")) ? jsObj.getString("data") : "";
				logger.error("状态码:{}, msg:{}, data:{}", code, msg, data);
				throw new BizException(code, msg, data);
			}
		} catch (Exception e) {
			logger.error("gpu服务器调用异常:{}", e.getMessage());
			throw new RuntimeException("服务器调用异常", e);
		}
	}

	@Override
	public List<TaskInfo> getTaskListData(TrainingServerDto serverDto) {
		String url = HTTP + serverDto.getIp() + "/api/getTaskList";
		HttpHeaders headers = this.initRestTemplateHeader();

		Map<String, Object> postParameters = new HashMap<>();
		String jsonBody = JSON.toJSONString(postParameters);
		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
		ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);

		// 返回结果
		String body = postForEntity.getBody();
		JSONObject jsObj = JSONObject.parseObject(body);
		if (jsObj.getInteger("code") != null && 200 == jsObj.getInteger("code")) {
			JSONArray jsonArray = jsObj.getJSONArray("data");
			return jsonArray.toJavaList(TaskInfo.class);
		} else {
			Integer ret = jsObj.getInteger("code") != null ? jsObj.getInteger("code") : 0;
			String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
			String data = StringUtils.isNotBlank(jsObj.getString("data")) ? jsObj.getString("data") : "";
			logger.error("状态码: " + ret + ", msg: " + msg + ", data: " + data);
			throw new BizException(ret, msg, data);
		}
	}

	@Override
	public String predictSegmentPic(TrainingServerDto serverDto, long taskId, String imgBase64, Long extparams) {
		String url = HTTP + serverDto.getIp() + "/predictPic";
		logger.info("图片预检测请求地址: {}",url);
		HttpHeaders headers = this.initRestTemplateHeader();
		Map<String, Object> postParameters = new HashMap<>();
		postParameters.put("taskid", taskId + "");
		postParameters.put("picdata", imgBase64);
		postParameters.put("threshold ", 0.4);
		// 音频检测时的额外参数
		if (extparams != null && extparams != 0) {
			postParameters.put("extparams", extparams);
		}
		String jsonBody = JSON.toJSONString(postParameters);
		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
		try {
			ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);
			// 返回结果
			String body = postForEntity.getBody();
			JSONObject jsObj = JSONObject.parseObject(body);
			if (jsObj.getInteger("ret") != null && 0 == jsObj.getInteger("ret")) {
				JSONArray jsonArray = jsObj.getJSONArray("predict");
				return jsonArray.toJavaList(String.class).get(0);
			} else {
				Integer ret = jsObj.getInteger("ret") != null ? jsObj.getInteger("ret") : 0;
				String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
				logger.error("状态码：{} , msg: {}",msg,ret);
			}
		} catch (Exception e) {
			logger.error("gpu服务器调用异常, [" + e.getMessage() + "]", e);
			throw new RuntimeException("gpu服务器调用异常", e);
		}
		return StringUtils.EMPTY;
	}
	
	@Override
	public List<PredictInfo> predictPic(TrainingServerDto serverDto, long taskId, String imgBase64, Long extparams) {
		String url = HTTP + serverDto.getIp() + "/predictPic";
		logger.info("图片预检测请求地址: " + url);
		HttpHeaders headers = this.initRestTemplateHeader();
		Map<String, Object> postParameters = new HashMap<>();
		postParameters.put("taskid", taskId + "");
		postParameters.put("picdata", imgBase64);
		postParameters.put("threshold ", 0.4);
		// 音频检测时的额外参数
		if (extparams != null && extparams != 0) {
			postParameters.put("extparams", extparams);
		}
		String jsonBody = JSON.toJSONString(postParameters);
		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
		try {
			ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);
			// 返回结果
			String body = postForEntity.getBody();
			JSONObject jsObj = JSONObject.parseObject(body);
			if (jsObj.getInteger("ret") != null && 0 == jsObj.getInteger("ret")) {
				JSONArray jsonArray = jsObj.getJSONArray("predict");
				return jsonArray.toJavaList(PredictInfo.class);
			} else {
				Integer ret = jsObj.getInteger("ret") != null ? jsObj.getInteger("ret") : 0;
				String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
				logger.error("状态码: " + ret + ", msg: " + msg);
			}
		} catch (Exception e) {
			logger.error("gpu服务器调用异常, [" + e.getMessage() + "]", e);
			throw new RuntimeException("gpu服务器调用异常", e);
		}
		return Collections.emptyList();
	}

	/**
	 * 初始化请求头 设置请求类型和接收类型
	 * 
	 * @return
	 */
	private HttpHeaders initRestTemplateHeader() {

		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);// 请求类型
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());// 接收类型
		return headers;
	}

	@Override
	public boolean serverIsOnline(TrainingServerDto serverDto, String projectType) {
		try {
			// 能正常调用说明gpu服务器正常

			if (ProjectConstant.PROJECT_TYPE_DATA_PREDICT.equals(projectType)) {
				this.getTaskListData(serverDto);
			} else if (StringUtils.equalsAnyIgnoreCase(projectType, ProjectConstant.IMG_TASK_TYPE)) {
				this.getTaskList(serverDto);
			} else if (ProjectConstant.PROJECT_TYPE_VOICE_CLASSIFY.equals(projectType)) {
				this.getTaskList(serverDto);
			}
			return true;
		} catch (Exception e) {
			logger.error("[" + serverDto.getIp() + "] 服务器不可用", e);
			return false;
		}
	}

//	public String getSdk(TrainingServerDto serverDto, TrainingTaskDto trainingTaskDto,
//			TrainingModelDto trainingModelDto) {
//		String url = HTTP + serverDto.getIp() + "/getSdk";
//		logger.info("离线模型文件生成请求地址: " + url);
//		HttpHeaders headers = this.initRestTemplateHeader();
//
//		Map<String, Object> postParameters = new HashMap<>();
//		// 使用模型关联的训练任务id(模型文件的文件名由训练任务的id生成,离线的模型文件要保存文件名一致)
//		postParameters.put("taskid", trainingTaskDto.getId().toString());
//		postParameters.put("tasktype", trainingTaskDto.getType().equals("9") ? 0L : Long.parseLong(trainingTaskDto.getType()));
//		postParameters.put("classnum", Long.parseLong(trainingTaskDto.getClassNum()));
//		postParameters.put("modelweight", trainingModelDto.getModelDir());
//		String jsonBody = JSON.toJSONString(postParameters);
//		logger.info("离线模型文件生成参数: " + jsonBody);
//		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
//		try {
//			ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);
//
//			// 返回结果
//			String body = postForEntity.getBody();
//			JSONObject jsObj = JSONObject.parseObject(body);
//			if (jsObj.getInteger("ret") != null && 0 == jsObj.getInteger("ret")) {
//				String sdkModelDir = jsObj.getString("sdkweight");
//				return sdkModelDir;
//			} else {
//				Integer ret = jsObj.getInteger("ret") != null ? jsObj.getInteger("ret") : 0;
//				String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
//				logger.error("状态码: " + ret + ", msg: " + msg);
//				throw new BizException(msg);
//			}
//		} catch (Exception e) {
//			logger.error("模型离线sdk文件生成异常, 模型id [" + trainingModelDto.getId() + "]", e);
//			throw new RuntimeException("模型离线sdk文件生成异常", e);
//		}
//	}

	@Override
	/**
	 * 启动预测任务,返回api路径
	 */
	public String predictData(long modelId,long predictTaskId) {
		//TODO  服务器列表，后面才实现
		TrainingServerDto serverDto =  new TrainingServerDto();
		serverDto.setIp("10.17.157.90:8012");

		String url = HTTP + serverDto.getIp() + "/api/" + modelId + "/predictBig";
		logger.info("数据预测请求地址: " + url);
		HttpHeaders headers = this.initRestTemplateHeader();
		Map<String, Object> postParameters = new HashMap<>();
		postParameters.put("predictId",predictTaskId);
		String jsonBody = JSON.toJSONString(postParameters);
		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
		ResponseEntity<String> postForEntity = null;
		try {
			postForEntity = restTemplate.postForEntity(url, r, String.class);
		} catch (Exception e) {
			logger.error(serverDto.getIp() + "启动预测任务 调用异常, [" + e.getMessage() + "]", e);
			throw new RuntimeException(serverDto.getIp() + " 服务器调用异常", e);
		}
		if (postForEntity != null) {
			// 返回结果
			String body = postForEntity.getBody();
			logger.info("启动预测任务 调用返回结果, [" + body + "]");
			JSONObject jsObj = JSONObject.parseObject(body);
			if (jsObj.getInteger("code") != null && 200 == jsObj.getInteger("code")) {
				JSONArray jsonArray = jsObj.getJSONArray("data");
				return url;
			} else {
				Integer code = jsObj.getInteger("code") != null ? jsObj.getInteger("code") : 0;
				String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
				String data = StringUtils.isNotBlank(jsObj.getString("data")) ? jsObj.getString("data") : "";
				logger.error("状态码: " + code + ", msg: " + msg + ", data: " + data);
				throw new BizException(msg);
			}
		} else {
			throw new BizException("出现未知道错误");
		}
	}

	public JSONArray predictData(TrainingServerDto serverDto, long taskId, JSONArray pData) {
		String url = HTTP + serverDto.getIp() + "/api/" + taskId + "/predict";
		logger.info("数据预测请求地址: " + url);
		HttpHeaders headers = this.initRestTemplateHeader();
		Map<String, Object> postParameters = new HashMap<>();
		postParameters.put("data", pData);
		String jsonBody = JSON.toJSONString(postParameters);
		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
		ResponseEntity<String> postForEntity = null;
		try {
			postForEntity = restTemplate.postForEntity(url, r, String.class);
		} catch (Exception e) {
			logger.error(serverDto.getIp() + " 调用异常, [" + e.getMessage() + "]", e);
			throw new RuntimeException(serverDto.getIp() + " 服务器调用异常", e);
		}
		if (postForEntity != null) {
			// 返回结果
			String body = postForEntity.getBody();
			JSONObject jsObj = JSONObject.parseObject(body);
			if (jsObj.getInteger("code") != null && 200 == jsObj.getInteger("code")) {
				JSONArray jsonArray = jsObj.getJSONArray("data");
				return jsonArray;
			} else {
				Integer code = jsObj.getInteger("code") != null ? jsObj.getInteger("code") : 0;
				String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
				String data = StringUtils.isNotBlank(jsObj.getString("data")) ? jsObj.getString("data") : "";
				logger.error("状态码: " + code + ", msg: " + msg + ", data: " + data);
				throw new BizException(msg);
			}
		} else {
			throw new BizException("出现未知道错误");
		}
	}

	@Override
	public boolean predictBigData(TrainingServerDto serverDto, long taskId, String predictId) {
		String url = HTTP + serverDto.getIp() + "/api/" + taskId + "/predictBig";
		logger.info("数据预测请求地址: " + url);
		HttpHeaders headers = this.initRestTemplateHeader();
		Map<String, Object> postParameters = new HashMap<>();

		postParameters.put("predictId", predictId);

		String jsonBody = JSON.toJSONString(postParameters);
		HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
		ResponseEntity<String> postForEntity = null;
		try {
			postForEntity = restTemplate.postForEntity(url, r, String.class);
		} catch (Exception e) {
			logger.error(serverDto.getIp() + " 调用异常, [" + e.getMessage() + "]", e);
			throw new RuntimeException(serverDto.getIp() + " 服务器调用异常", e);
		}
		if (postForEntity != null) {
			// 返回结果
			String body = postForEntity.getBody();
			JSONObject jsObj = JSONObject.parseObject(body);
			if (jsObj.getInteger("code") != null && 200 == jsObj.getInteger("code")) {
//				JSONArray jsonArray = jsObj.getJSONArray("data");
				return true;
			} else {
				Integer code = jsObj.getInteger("code") != null ? jsObj.getInteger("code") : 0;
				String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
				String data = StringUtils.isNotBlank(jsObj.getString("data")) ? jsObj.getString("data") : "";
				logger.error("状态码: " + code + ", msg: " + msg + ", data: " + data);
				throw new BizException(msg);
			}
		} else {
			throw new BizException("出现未知道错误");
		}
	}


//
//	@Override
//	public String getDataSdk(TrainingTaskDataDto trainingTaskDto, TrainingModelDataDto trainingModelDto) throws IOException {
//		Long modelId = trainingModelDto.getId();
//		String type = trainingTaskDto.getType() == "0" ? "分类" : "回归"; // 先默认直接
//		String algorithm = trainingTaskDto.getArithmetic();
//		String maps = trainingModelDto.getClassifier(); // 这个位置未确定从哪里拿所以先为空
//		JSONObject mapObjects = JSONObject.parseObject(maps);
//		JSONObject label = mapObjects.getJSONObject("label");
//		JSONObject feature = mapObjects.getJSONObject("feature");
//		JSONArray variableNameArray = mapObjects.getJSONArray("feature_name");
//		JSONArray dateNameArray = mapObjects.getJSONArray("date_name");
//		String target = mapObjects.getString("label_name");
//		String modelName = trainingModelDto.getModelName();
//		String modelDir = trainingModelDto.getModelDir();
//		JSONObject configJSON = new JSONObject();
//		configJSON.put("model_id", modelId);
//		configJSON.put("type", type);
//		configJSON.put("algorithm", algorithm);
//		configJSON.put("variable_name", variableNameArray);
//		configJSON.put("date_name", dateNameArray);
//		configJSON.put("target_name", target);
//		configJSON.put("label_map", label);
//		configJSON.put("feature_map", feature);
//		configJSON.put("model_name", modelName);
//		configJSON.put("model_dir", modelDir);
//		Random r = new Random();
//
//		String sdkModelPath = sdkPath + File.separator + modelId.toString() + "_" + System.currentTimeMillis() + "_"
//				+ r.nextLong() + File.separator;
//
//		TxtUtil.creatTxt(sdkModelPath, "config.json", JSON.toJSONString(configJSON, SerializerFeature.PrettyFormat,
//				SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat));
//
//		String configPath = sdkModelPath + "config.json";
//
//		File modelFile = null;
//		try {
//			modelFile = ossUtil.downloadFile(sdkModelPath, modelDir);
//		} catch (Exception e) {
//			logger.error("从oss下载文件  {} 失败", modelName, e);
//			throw new RuntimeException("服务器下载模型文件失败", e);
//		}
//		String zipModelName = modelName + ".zip";
//		String zipFilePath = sdkModelPath + zipModelName;
//
//		File configFile = new File(configPath);
//		List<File> srcFiles = new ArrayList<>();
//		srcFiles.add(configFile);
//		srcFiles.add(modelFile);
//
//		boolean isZipSuccess = ZipUtil.zipFile(zipFilePath, srcFiles);
//		if (isZipSuccess) {
//			File zipFile = new File(zipFilePath);
//			try {
//				ossUtil.putObject(zipModelName, zipFile);
//			} catch (Exception e) {
//				logger.error("{} 上传到oss失败", zipModelName, e);
//				throw new RuntimeException("oss上传文件失败", e);
//			}
//		}
//
//		return zipModelName;
//	}

	@SuppressWarnings("unused")
	private Path getConfPath(String fileName) {
		return Paths.get(sdkPath, fileName);
	}
	@SuppressWarnings("unused")
	private Path getConfPath(String path, String fileName) {
		return Paths.get(path, fileName);
	}

}